#include "audioplayer.h"
#include <QMutexLocker>
#include <QDebug>

AudioPlayer* AudioPlayer::m_pInstance = nullptr;
QMutex AudioPlayer::m_audioPlayMutex;
AudioPlayer::Garbage AudioPlayer::m_garbage;

AudioPlayer *AudioPlayer::instance()
{
    QMutexLocker locker(&m_audioPlayMutex);
    if (m_pInstance == nullptr) {
        m_pInstance = new AudioPlayer;
    }

    return m_pInstance;
}

AudioPlayer::AudioPlayer()
{

}

void AudioPlayer::StartAudioPlayer() {
    QMutexLocker locker(&m_audioPlayMutex);

    QAudioFormat fmat;

    fmat.setChannelCount(m_channel);
    fmat.setSampleSize(m_sampleSize);
    fmat.setSampleRate(m_sampleRate);
    fmat.setCodec("audio/pcm");
    fmat.setByteOrder(QAudioFormat::LittleEndian);
    fmat.setSampleType(QAudioFormat::SignedInt);

    m_pAudioOutput = new QAudioOutput(fmat);

    QAudioDeviceInfo devinfo = QAudioDeviceInfo::defaultOutputDevice();
    if (devinfo.isFormatSupported(fmat))
        fmat = devinfo.nearestFormat(fmat);

    m_pIODevice = m_pAudioOutput->start();
}

void AudioPlayer::StopAudioPlayer()
{
    QMutexLocker locker(&m_audioPlayMutex);

    if (m_pAudioOutput != nullptr) {
        m_pAudioOutput->stop();
        delete m_pAudioOutput;
        m_pAudioOutput = nullptr;
    }
}

int AudioPlayer::getFreeSpace()
{
    QMutexLocker locker(&m_audioPlayMutex);

    if (!m_pAudioOutput) {
        return 0;
    }

    int freeSpace = m_pAudioOutput->bytesFree();

    return freeSpace;
}

void AudioPlayer::setVolume(int value)
{
    QMutexLocker locker(&m_audioPlayMutex);
    if (!m_pAudioOutput) {
        return;
    }
    m_pAudioOutput->setVolume(value);
}

void AudioPlayer::setMuted(bool muted)
{
    QMutexLocker locker(&m_audioPlayMutex);
    if (!m_pAudioOutput) {
        return;
    }
    if (muted) {
        m_pAudioOutput->setVolume(0);
    } else {
        m_pAudioOutput->setVolume(100);
    }
}

bool AudioPlayer::WriteAudioData(const char *dataBuff, int size)
{
    QMutexLocker locker(&m_audioPlayMutex);
    if((dataBuff == nullptr) || (size <= 0)){
        return false;
    }

    if(m_pIODevice == nullptr){
        return false;
    }

    m_pIODevice->write(dataBuff,size);

    return true;
}

void AudioPlayer::playAudio(bool play)
{
    QMutexLocker locker(&m_audioPlayMutex);
    if( m_pAudioOutput == nullptr){
        return;
    }

    if(play){
        m_pAudioOutput->resume();
    } else{
        m_pAudioOutput->suspend();
    }
}
